package org.jradweb.tools.generator.maven;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.jradweb.tools.generator.utils.PropertiesLoader;
import org.unitils.dbmaintainer.script.impl.DefaultScriptParser;



/**
 * for execute database script that init database
 * 
 * @goal initDB
 * @phase process-test-resources
 */
public class InitDBMojo extends AbstractMojo {
	/**
	 * ${project.build.directory}
	 * 
	 * @parameter expression="${project.build.directory}"
	 */
	private File buildPath;
	/**
	 * @parameter expression="${basedir}"
	 */
	private File baseDir;

	/**
	 * @parameter expression="${project.groupId}"
	 */
	private String groupId;
	
	/**
	 * @parameter expression="${project.artifactId}"
	 */
	private String artifactId;

	public void execute() throws MojoExecutionException, MojoFailureException {
		PropertiesLoader loader = new PropertiesLoader(this.baseDir,
				this.artifactId);
		// load database connection parameters
		Properties props = null;
		try {
			props = loader.loadProjectProperties();
		} catch (FileNotFoundException e) {
			throw new MojoFailureException("load " + this.artifactId
					+ ".properties failed. message:" + e.getMessage());
		} catch (IOException e) {
			throw new MojoFailureException("load " + this.artifactId
					+ ".properties failed. message:" + e.getMessage());
		}

		Connection conn =null;
		try {
			Class driverClass = Class.forName(props
					.getProperty(PropertiesLoader.DATABASE_DRIVER_CLASS_NAME));
			conn = DriverManager.getConnection(props
					.getProperty(PropertiesLoader.DATABASE_URL), props
					.getProperty(PropertiesLoader.DATABASE_USER_NAME), props
					.getProperty(PropertiesLoader.DATABASE_PASSWORD));
			
			Statement stmt=conn.createStatement();
			List<File> sfs=this.getScriptFiles();
			
			
			DefaultScriptParser ssp=new DefaultScriptParser();
			for(File sf:sfs){
				this.getLog().info("Execute file: "+sf.getAbsolutePath());
				String script=this.getScript(sf);
//				List<String> commands=ssp.parseStatements(script);
//				for(String c:commands)
//				{
//					stmt.executeUpdate(c);
//				}
			}
			stmt.executeUpdate("SET FOREIGN_KEY_CHECKS=0");
		} catch (ClassNotFoundException e) {
			throw new MojoFailureException(
					"get database connection failed. message:" + e.getMessage());
		} catch (SQLException e) {
			throw new MojoFailureException(
					"get database connection failed. message:" + e.getMessage());
		}
		catch (IOException e) {
			throw new MojoFailureException(
					"read script file filed:" + e.getMessage());
		}finally{
			
			try {
				if(conn!=null)
					conn.close();
			} catch (SQLException e) {
				throw new MojoFailureException(
						"colse connection failed:" + e.getMessage());
			}
		}
	}
	
	public String getScript(File file) throws IOException{
		java.io.InputStream in=null;
		try {
			in=new FileInputStream(file);
			StringBuffer sb=new StringBuffer();
			byte buffer[]=new byte[1024];
			int i=1;
			while(i>0){
				i=in.read(buffer);
				if(i>0){
					byte[] temp=new byte[i];
					for(int n=0;n<i;n++){
						temp[n]=buffer[n];
					}
					sb.append(new String(temp,"UTF-8"));
				}
			}
			
			
			return sb.toString();
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		}finally{
			if(in!=null){
				in.close();
			}
		}
	}
	
	public List<File> getScriptFiles(){
		List<File> files=new ArrayList<File>();
		File dbPath = new File(this.baseDir.getAbsolutePath()
				+ "/src/main/config/db");
		
		if(!dbPath.exists()){
			dbPath.mkdirs();
		}
		
		File[] vfs=dbPath.listFiles();
		if(vfs!=null&&vfs.length>0){
			for(File vf:vfs){
				if(vf.getName().startsWith("1.")&&vf.isDirectory()){
					File[] sfs=vf.listFiles();
					if(sfs!=null&&sfs.length>0){
						for(File fs:sfs){
							if(fs.getName().endsWith(".sql")){
								files.add(fs);
							}
						}
					}
				}
					
			}
		}
		
		return files;
	}
	public static void main(String[] args) throws Exception{
		InitDBMojo idm=new InitDBMojo();
		idm.artifactId = "easycrm";
		idm.groupId = "com.infowarelab";
		idm.baseDir = new File("d:/workspace2/easycrm/");
		idm.execute();
//		List<File> files=idm.getScriptFiles();
//		for(File f:files){
//			System.out.println(f.getAbsolutePath());
//			System.out.println("_-----------------------------------------------------");
//			System.out.println(idm.getScript(f));
//		}
	}
	
}
